﻿
Imports System.IO

'a simple virtdisk, support read & write a certain length, not follow the sector size 512
Public Class virtdisk
    Private s As Stream = Nothing

    Public Function valid() As Boolean
        Return Not s Is Nothing AndAlso s.CanRead AndAlso s.CanWrite AndAlso s.CanSeek
    End Function

    Public Function close() As Boolean
        closestream(s)
        Return True
    End Function

    Public Function open(ByVal filename As String) As Boolean
        Try
            s = New FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read)
            Return True
        Catch ex As Exception
            raiseError("cannot open file " + filename + ", ex " + ex.Message, errorHandle.errorType.exclamation)
            Return False
        End Try
    End Function

    Public Function read(ByVal start As Int64, ByVal length As Int64, ByRef output As bytes) As Boolean
        If Not valid() OrElse start < 0 OrElse length < 0 OrElse start + length > s.Length Then
            Return False
        End If
        If length = 0 Then
            If output Is Nothing Then
                output = New bytes()
            Else
                output.clear()
            End If
            output.size = length
            Return True
        End If
        Return readstream(s, output, start, length) = length
    End Function

    Public Function write(ByVal start As Int64, ByVal input As bytes) As Boolean
        If Not valid() OrElse input Is Nothing OrElse start < 0 Then
            Return False
        End If
        If input.size = 0 Then
            Return True
        End If
        s.Position = start
        Return writestream(s, +input)
    End Function

    Public Function fill(ByVal start As Int64, ByVal length As Int64) As Boolean
        If Not valid() Then
            Return False
        End If
        If s.Length < start + length Then
            Try
                s.SetLength(start + length)
            Catch ex As Exception
                raiseError("cannot fill virtdisk, ex " + ex.Message, errorHandle.errorType.exclamation)
                Return False
            End Try
        End If
        Return True
    End Function

    Public Function [erase](ByVal start As Int64) As Boolean
        If Not valid() Then
            Return False
        End If
        If s.Length > start Then
            Try
                s.SetLength(start)
            Catch ex As Exception
                raiseError("cannot erase virtdisk, ex " + ex.Message, errorHandle.errorType.exclamation)
                Return False
            End Try
        End If
        Return True
    End Function

    Public Function flush() As Boolean
        If Not valid() Then
            Return False
        End If
        s.Flush()
        Return True
    End Function
End Class
